package io.renren.modules.ws.controller;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.*;
import org.springframework.messaging.simp.SimpMessagingTemplate;

import org.springframework.stereotype.Controller;

import java.util.Map;

@Controller
public class StompController {
    static Logger log = LoggerFactory.getLogger(StompController.class);

    //spring提供的推送方式
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 广播主题
     * @param message
     * @param topic
     *
     * 注册广播监听
     * stompClient.subscribe('/topic/test', (res) => {
     * 	    console.info('topic-test', res)
     *  })
     *  发送广播监听 test 就是 ${topic}值
     * stompClient.send("/application/toPublic/test", {}, $("#msg").val())
     */
    @MessageMapping("/toPublic/{topic}")
    public void toPublic(String message, @DestinationVariable String topic) {
        log.info("[toPublic]-[" + topic + "]-消息:" + message);
        String channel = "/topic/" + topic;
        simpMessagingTemplate.convertAndSend(channel, message);
    }

    /**
     * 点对点主题
     * @param message
     * @param MessageHeaders
     * @param destination
     * @param headers
     * @param id
     * @param body
     *
     * 前端监听 /user/queue/message
     *
     * 前端触发地址
     * 前缀/toUser/主题/目标人
     * /application/toUser/message/
     *
     * 注意： queue是必须的！
     */
    @MessageMapping("/toUser/{topic}/{id}")
    public void toUser(Message message,
                       MessageHeaders MessageHeaders,
                       @Header("destination") String destination,
                       @Headers Map<String, Object> headers,
                       @DestinationVariable String topic,
                       @DestinationVariable String id,
                       @Payload String body) {
        log.info("[toUser]-[" + topic + "]-[" + id +"]-消息:" + body);
        String channel = "/queue/" + topic;
        System.out.println(channel);
        simpMessagingTemplate.convertAndSendToUser(id, channel, body);
    }

}
